#include "queue.hpp"
#include <algorithm>

const char *Queue::getPriorityString(Command *comm)
{
	if(!comm)
		throw Queue::Exception(Queue::Exception::NULL_COMMAND,
		                       "a null (*Command) passed");

	switch(comm->_priority) {
	case Command::HIGH_PRIORITY:
		return "HIGH PRIORITY";
	case Command::HALF_PRIORITY:
		return "HALF PRIORITY";
	case Command::LOW_PRIORITY:
		return "LOW PRIORITY";
	default:
		return "UNKNOW PRIORITY";
	}
}

void Queue::setPriority(Command *comm, int priority)
{
	if(!comm)
		throw Queue::Exception(Queue::Exception::NULL_COMMAND,
		                       "a null (*Command) passed");
	comm->_priority = priority;
}

int Queue::getPriority(Command *comm)
{
	if(!comm)
		throw Queue::Exception(Queue::Exception::NULL_COMMAND,
		                       "a null (*Command) passed");
	return comm->_priority;
}

void Queue::pushCommand(Command *comm)
{
	if(!comm)
		throw Queue::Exception(Queue::Exception::NULL_COMMAND,
		                       "a null (*Command) passed");
	_commands.push_back(comm);
}

void Queue::schedule()
{
	std::sort(_commands.begin(),_commands.end(), prioritySort);
}

void Queue::execQueue()
{
	Command *c = NULL;
	while(!_commands.empty()) {
		schedule();

		c = _commands.front();
		c->execute();

		_commands.pop_front();
	}
}
